<template>
	<view>
		<u-form>
			<u-form-item v-for="item in fields" :key="item.id">
				<u-cell
					:isLink="item.type != 'text'"
					rightIconStyle="font-size: 40rpx;"
					:title="item.name"
					@click="cellClick(item)"
				>
					<template slot="value">
						<u-text v-if="item.type != 'number'" :lines="1" size="32" :text="form[item.prop]" />
						<u-input
							v-else="item.type == 'number'"
							v-model="form[item.prop]"
							border="none"
							inputAlign="right"
							suffixIcon="小时"
							suffixIconStyle="font-size:32rpx"
							type="number"
						/>
					</template>
				</u-cell>
			</u-form-item>
		</u-form>

		<u-datetime-picker
			:closeOnClickOverlay="true"
			mode="datetime"
			:mode="datePickerMode"
			:show="datePickerVisible"
			:value="form[datePickerKey]"
			@cancel="closeDatePicker"
			@close="closeDatePicker"
			@confirm="onDateChange"
		/>

		<view class="fixed--bottom">
			<u-button shape="circle" type="primary" @click="chargeAppoint">预约充电</u-button>
			<u-button v-if="status == 0" shape="circle" @click="cancelAppoint">取消预约</u-button>
		</view>
	</view>
</template>

<script>
const { reservation, isChargingAllowed, accept, reservationPages } = require('@/api/private');
const { isOverTime } = require('@/homeSub/pages/siteDetail/util.js');
export default {
	data() {
		let uid = 0;
		const fields = [
			{ name: '充电站', type: 'text', prop: 'station', id: uid++, value: '' },
			{ name: '充电桩', type: 'text', prop: 'pileName', id: uid++, value: '' },
			{
				name: '预约日期',
				type: 'date',
				mode: 'date',
				prop: 'date',
				id: uid++,
				value: uni.$u.timeFormat(Date.now(), 'yyyy-mm-dd')
			},
			{
				name: '预约时间',
				type: 'date',
				mode: 'time',
				prop: 'time',
				id: uid++,
				value: uni.$u.timeFormat(Date.now(), 'hh:MM:ss')
			},
			{ name: '充电时长', type: 'number', prop: 'duration', id: uid++, value: '' }
		];
		return {
			fields,
			form: fields.reduce((prev, current) => {
				prev[current.prop] = current.value;
				return prev;
			}, {}),
			datePickerVisible: false,
			currentField: null,
			info: {},
			status: -1
		};
	},
	onLoad(options) {
		this.form.station = options.name;
		this.form.pileId = options.pileId;
		this.form.pileName = options.pileName;
		this.reservationPages();
	},
	computed: {
		datePickerMode() {
			return this.currentField?.mode || 'date';
		},
		datePickerKey() {
			return this.currentField?.prop || 'date';
		}
	},
	methods: {
		reservationPages() {
			return reservationPages({ current: 1, pageSize: 10 }).then((res) => {
				this.reservations = res.data.records.filter((r) =>
					isOverTime(r.reservationStartTime, r.chargingDuration, Date.now())
				);
				// 待审核、审核通过
				this.reservations = this.reservations.filter((r) => [0, 1].includes(+r.state));
				this.isChargingAllowed();
				console.log(this.reservations);
			});
		},

		isChargingAllowed() {
			if (this.reservations.length == 0) return;
			Object.assign(this.info, this.reservations[0], this.form);
			let date = this.info.createTime.split(' ');
			this.status = this.info.state ?? -1;
			this.form.date = date[0] || uni.$u.timeFormat(Date.now(), 'yyyy-mm-dd');
			this.form.time = date[1] || uni.$u.timeFormat(Date.now(), 'hh:MM:ss');
			this.form.duration = this.info.chargingDuration || 0;
		},
		onDateChange(e) {
			if (e.mode == 'date') {
				this.form[e.mode] = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
			} else {
				this.form[e.mode] = e.value.padEnd(8, ':00');
			}
			this.closeDatePicker();
		},
		cellClick(item) {
			if (item.type == 'date') {
				this.currentField = item;
				this.datePickerVisible = true;
			}
		},
		closeDatePicker() {
			this.datePickerVisible = false;
		},
		toSeeStatus() {
			uni.navigateTo({
				url: 'appointmentStatus?status=' + this.status,
				success: (res) => {
					res.eventChannel.emit('data', this.info);
				}
			});
		},
		chargeAppoint() {
			if ([0, 1, 2, 3].includes(this.status)) return this.toSeeStatus();
			if (!this.form.duration) return uni.showToast({ icon: 'none', title: '请填写充电时长！' });
			const { pileId, date, time, duration } = this.form;
			reservation({
				pileId: +pileId,
				chargingDuration: duration,
				reservationStartTime: `${date} ${time}`
			}).then(async (res) => {
				if (res.code == 0) {
					this.status = 0;
					await this.reservationPages();
					this.toSeeStatus();
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			});
		},
		cancelAppoint() {
			if (!this.info.id) return uni.showToast({ icon: 'none', title: '您还没有预约充电！' });
			accept([{ id: this.info.id, state: 4 }]).then((res) => {
				if (res.code == 0) {
					uni.showToast({ icon: 'none', title: '您已取消预约充电！' });
					uni.navigateBack();
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.fixed--bottom {
	position: fixed;
	bottom: 70rpx;
	left: 0;
	right: 0;
	display: flex;
	flex-direction: column;
	row-gap: 50rpx;
	padding: 0 30rpx;
}
</style>
